#!/usr/bin/env groovy

def lib
// Currently the loadbalancer service is not working on minikube, same for network policies
def DEFAULT_EXCLUDED_GROUPS = "loadbalancer,networkpolicies"

pipeline {
    agent {
        node {
            label "strimzi-pr"
        }
    }
    parameters {
        string(name: 'TEST_CASE', defaultValue: '*ST', description: 'maven parameter for executing specific tests')
        string(name: 'TEST_PROFILE', defaultValue: 'acceptance', description: 'maven parameter for executing specific test profile')
        string(name: 'EXCLUDE', defaultValue: "${DEFAULT_EXCLUDED_GROUPS}", description: 'maven parameter for exclude specific test tag')
        string(name: 'ENV_VARS', defaultValue: "", description: 'maven parameter for setting values of environment variables used in STs')
    }
    options {
        timeout(time: 24, unit: 'HOURS')
        ansiColor('xterm')
    }
    environment {
        ARTIFACTS_DIR = 'systemtest/target/logs'
        JOB_NAME_SUB = "${String.format("%.15s", JOB_NAME).toLowerCase()}"
        ORIGIN_BASE_DIR = "${env.WORKSPACE}/origin/"
        KUBE_CONFIG_PATH = "${env.WORKSPACE}/origin/kube-apiserver/admin.kubeconfig"
        OPERATOR_IMAGE_PULL_POLICY = "IfNotPresent"
        COMPONENTS_IMAGE_PULL_POLICY = "IfNotPresent"
        JAVA_VERSION = "11"
        TEST_HELM2_VERSION = "v2.17.0"
        TEST_HELM3_VERSION = "v3.4.2"
        TEST_CLUSTER = "minikube"
    }
    stages {
        stage('Clean WS') {
            steps {
                cleanWs()
            }
        }
        stage('Checkout Strimzi') {
            steps {
                checkout scm
            }
        }
        stage('Parse parameters from comment') {
            steps {
                script {
                    lib = evaluate readFile('./.jenkins/jenkins.groovy')
                    println("Comment body: ${env.ghprbCommentBody}")
                    env.TEST_CASE = params.TEST_CASE
                    env.TEST_PROFILE = params.TEST_PROFILE
                    env.ENV_VARS = params.ENV_VARS
                    env.EXCLUDE_GROUPS = DEFAULT_EXCLUDED_GROUPS
                    if (env.ghprbCommentBody.contains('testcase=')) {
                        env.TEST_CASE = env.ghprbCommentBody.split('testcase=')[1].split(/\s/)[0]
                    }
                    println("TEST_CASE: ${env.TEST_CASE}")
                    if (env.ghprbCommentBody.contains('profile=')) {
                        env.TEST_PROFILE = env.ghprbCommentBody.split('profile=')[1].split(/\s/)[0]
                        if (env.TEST_PROFILE != "flaky") {
                            env.EXCLUDE_GROUPS = env.EXCLUDE_GROUPS + ",flaky"
                        }
                    }
                    println("TEST_PROFILE: ${env.TEST_PROFILE}")
                    if (env.ghprbCommentBody.contains('exclude=')) {
                        env.EXCLUDE_GROUPS = env.EXCLUDE_GROUPS + ',' + env.ghprbCommentBody.split('exclude=')[1].split(/\s/)[0]
                    }
                    println("EXCLUDE_GROUPS: ${env.EXCLUDE_GROUPS}")
                    if (env.ghprbCommentBody.contains('test_only')) {
                        env.TEST_ONLY = "true"
                        env.DOCKER_REGISTRY = "quay.io"
                        env.DOCKER_ORG="strimzi"
                        env.DOCKER_TAG = "latest"
                    } else {
                        env.TEST_ONLY = "false"
                        env.DOCKER_ORG="strimzi"
                        env.DOCKER_REGISTRY = "localhost:5000"
                        env.DOCKER_TAG="pr"
                    }
                    if (env.ghprbCommentBody.contains('install_type=')) {
                        env.CLUSTER_OPERATOR_INSTALL_TYPE = env.ghprbCommentBody.split('install_type=')[1].split(/\s/)[0]
                    }
                    if (env.ghprbCommentBody.contains('env=')) {
                        env.ENV_VARS = env.ghprbCommentBody.split('env=')[1]
                        for (envVar in "${env.ENV_VARS}".split(",")) {
                            env.(envVar.split("=")[0]) = envVar.split("=")[1]
                            println("${env.(envVar.split("=")[0])}")
                        }
                    }
                    if (env.ghprbCommentBody.contains('kube_version=')) {
                        env.KUBE_VERSION = env.ghprbCommentBody.split('kube_version=')[1].split(/\s/)[0]
                    } else {
                        // Default version (the oldest supported by Strimzi)
                        env.KUBE_VERSION = "stable"
                    }
                    println("ENV_VARS: ${env.ENV_VARS}")
                    env.BUILD_PROJECT_STATUS = false
                    env.BUILD_DOCKER_IMAGE_STATUS = false
                    println("TEST_ONLY: ${env.TEST_ONLY}")
                    println("DOCKER_REGISTRY: ${env.DOCKER_REGISTRY}")
                    println("DOCKER_ORG: ${env.DOCKER_ORG}")
                    println("DOCKER_TAG: ${env.DOCKER_TAG}")
                    println("CLUSTER_OPERATOR_INSTALL_TYPE: ${env.CLUSTER_OPERATOR_INSTALL_TYPE}")
                    println("KUBE_VERSION: ${env.KUBE_VERSION}")
                }
            }
        }
        stage('Start Minikube') {
            steps {
                timeout(time: 10, unit: 'MINUTES') {
                    script {
                        lib.setupKubernetes()
                    }
                }
            }
        }
        stage('Install Helm') {
            steps {
                timeout(time: 10, unit: 'MINUTES') {
                    script {
                        lib.installHelm(env.WORKSPACE)
                    }
                }
            }
        }
        stage('Install yq') {
            steps {
                timeout(time: 5, unit: 'MINUTES') {
                    script {
                        lib.installYq(env.WORKSPACE)
                    }
                }
            }
        }
        stage('Build project') {
            steps {
                script {
                    withMaven(mavenOpts: '-Djansi.force=true') {
                        sh(script: "mvn clean install -DskipTests -Dstyle.color=always --no-transfer-progress")
                        env.BUILD_PROJECT_STATUS = true
                    }
                }
            }
        }
        stage('Build images') {
            when {
                environment name: 'TEST_ONLY', value: 'false'
            }
            steps {
                script {
                    lib.buildStrimziImages()
                    env.BUILD_DOCKER_IMAGE_STATUS = true
                    env.DOCKER_REGISTRY = sh(script: "kubectl get service registry -n kube-system -o=jsonpath='{.spec.clusterIP}'", returnStdout: true).trim() + ":80"
                    println("DOCKER_REGISTRY: ${env.DOCKER_REGISTRY}")
                }
            }
        }
        stage('Execute system tests') {
            steps {
                script {
                    catchError {
                        // For upgrade tests running with locally built images we need to change tag in StrimziUpgradeST.json
                        if ("${env.TEST_PROFILE}".contains("upgrade")) {
                            println("[INFO] Update files for upgrade procedure")
                            sh(script: """
                                sed -i 's#:latest#:${env.DOCKER_TAG}#g' ${env.WORKSPACE}/systemtest/src/test/resources/upgrade/StrimziUpgradeST.json ${env.WORKSPACE}/install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
                                sed -i 's#quay.io/strimzi/test-client:${env.DOCKER_TAG}#${env.DOCKER_REGISTRY}/strimzi/test-client:${env.DOCKER_TAG}#g' ${env.WORKSPACE}/systemtest/src/test/resources/upgrade/StrimziUpgradeST.json
                                sed -i 's#quay.io/strimzi/#${env.DOCKER_REGISTRY}/strimzi/#g' ${env.WORKSPACE}/install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
                                sed -i 's#/opt/${env.DOCKER_REGISTRY}#/opt#g' ${env.WORKSPACE}/install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml
                            """)
                            sh(script: "cat ${env.WORKSPACE}/systemtest/src/test/resources/upgrade/StrimziUpgradeST.json")
                            sh(script: "cat ${env.WORKSPACE}/install/cluster-operator/060-Deployment-strimzi-cluster-operator.yaml")
                        }
                        lib.runSystemTests(env.WORKSPACE, env.TEST_CASE, env.TEST_PROFILE, env.EXCLUDE_GROUPS)
                    }
                }
            }
        }
    }
    post {
        always {
            script {
                sh(script: "sudo ./systemtest/scripts/results_info.sh ./systemtest/target/failsafe-reports/ ${env.TEST_CASE} ${env.TEST_PROFILE} ${env.BUILD_NUMBER} ${env.KUBE_VERSION} ${env.TEST_ONLY} ${env.EXCLUDE_GROUPS} ${env.ENV_VARS}")
                lib.postGithubPrComment("results.json")
                lib.postAction(env.ARTIFACTS_DIR, env.ghprbPullId, env.ghprbActualCommitAuthor, env.ghprbPullTitle, env.ghprbPullLink, env.BUILD_URL, env.WORKSPACE, env.STRIMZI_MAILING_LIST)
            }
        }
        failure {
            println("Build failed")
            script {
                lib.sendMail(env.STRIMZI_MAILING_LIST, "failed", env.ghprbPullId, env.ghprbActualCommitAuthor, env.ghprbPullTitle, env.ghprbPullLink, env.BUILD_URL)
            }
        }
    }
}
